package cn.pomelo.signal.quartZ.util;

import cn.pomelo.signal.common.Constants;
import cn.pomelo.signal.model.SJob;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.BeanUtils;

import java.util.Date;

public abstract class AbstractQuartzJob implements Job {

    /**
     * 线程本地变量
     */
    private static final ThreadLocal<Date> threadLocal = new ThreadLocal<>();

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        SJob job = new SJob();
        BeanUtils.copyProperties(context.getMergedJobDataMap().get(Constants.TASK_PROPERTIES), job);
        try {
            before(context, job);
            if (job != null) {
                doExecute(context, job);
            }
            after(context, job);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    protected void before(JobExecutionContext context, SJob job) {
        threadLocal.set(new Date());
    }

    protected void after(JobExecutionContext context, SJob job) {
        threadLocal.remove();
    }

    protected abstract void doExecute(JobExecutionContext context, SJob job) throws Exception;
}
